package com.rightsidetech.http.controller.storeApp.trade;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.rightsidetech.activity.service.ActCouponUserService;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.http.config.WechatConfig;
import com.rightsidetech.http.wechatutil.WeChatRefundUtils;
import com.rightsidetech.mall.entity.MallCommoditySpecs;
import com.rightsidetech.mall.service.MallCommodityService;
import com.rightsidetech.trade.dtos.request.AppAfterSaleRecordReq;
import com.rightsidetech.system.dtos.request.store.StoreCommodityIntegralDetialReq;
import com.rightsidetech.system.dtos.request.store.StoreCommodityIntegralReq;
import com.rightsidetech.trade.dtos.response.AppAfterSaleRecordResp;
import com.rightsidetech.system.entity.store.*;
import com.rightsidetech.system.service.SysStoreInfoService;
import com.rightsidetech.system.service.SysStoreIntegralService;
import com.rightsidetech.system.service.SysStoreLoginInfoService;
import com.rightsidetech.system.service.SysStoreStorkService;
import com.rightsidetech.trade.dtos.request.TdCheckAfterServiceReq;
import com.rightsidetech.trade.dtos.request.TdCommodityOrderNoRequest;
import com.rightsidetech.trade.dtos.request.TdCommodityStoreAppListRequest;
import com.rightsidetech.trade.dtos.response.TdCommodityStoreAppListResp;
import com.rightsidetech.trade.dtos.response.TdCommodityStoreOrderDetailResp;
import com.rightsidetech.trade.entity.TdCommodityOrderDetails;
import com.rightsidetech.trade.entity.TdCommodityTradeOrder;
import com.rightsidetech.trade.entity.TdCommodityUserOrder;
import com.rightsidetech.trade.service.TdCommodityUserOrderService;
import com.rightsidetech.trade.service.TdCouponUseService;
import com.rightsidetech.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/storeApp/trade")
@ShenyuSpringMvcClient(path = "/storeApp/trade/**")
@Api(tags = "门店订单相关")
public class TdCommodityStoreAppController extends BaseController {

    @Resource
    private TdCommodityUserOrderService tdCommodityUserOrderService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private SysStoreLoginInfoService sysStoreLoginInfoService;
    @Autowired
    private WechatConfig wechatConfig;
    @Resource
    private SysStoreIntegralService sysStoreIntegralService;
    @Resource
    private SysStoreStorkService sysStoreStorkService;
    @Resource
    private MallCommodityService mallCommodityService;
    @Resource
    private TdCouponUseService tdCouponUseService;
    @Resource
    private ActCouponUserService actCouponUserService;

    @Log
    @Token
    @ApiOperation("门店订单列表")
    @GetMapping("/page")
    @ApiOperationSupport(ignoreParameters = {"storeId"})
    public ResponseData<PageInfo<TdCommodityStoreAppListResp>> page(TdCommodityStoreAppListRequest req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        req.setStoreId(Long.parseLong(getAttribute()));
        PageInfo<TdCommodityStoreAppListResp> pageInfo = tdCommodityUserOrderService.findOrderByStore(req);
        if (!StringUtils.isEmpty(pageInfo.getList()) && pageInfo.getList().size() > 0) {
            for (TdCommodityStoreAppListResp appListResp : pageInfo.getList()) {
                String headImg = userInfoService.getHeadImg(appListResp.getUserInfoId());
                appListResp.setHeadImg(headImg);
            }
        }

        return ResponseData.success(pageInfo);
    }

    @Log
    @Token
    @ApiOperation("接单")
    @PostMapping("/receiveOder")
    public ResponseData receiveOrder(@RequestBody TdCommodityOrderNoRequest req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderService.findByOrderNo(req.getOrderNo());
        if (StringUtils.isEmpty(tdCommodityUserOrder)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        if (tdCommodityUserOrder.getStoreId() != Long.parseLong(getAttribute())) {
            return ResponseData.fail("不是该门店的订单");
        }
        if (tdCommodityUserOrder.getOrderStatus() != 1) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }

        //添加出库记录, 判断是否到店自取
        if(tdCommodityUserOrder.getOrderType() != 1){
            updateStoreInfo(tdCommodityUserOrder.getOrderNo(),tdCommodityUserOrder.getStoreId());
        }

        return tdCommodityUserOrderService.receiveOrder(req.getOrderNo(), Long.parseLong(getAttribute()));
    }

    private void updateStoreInfo(String orderNo,Long storeId){
        List<TdCommodityOrderDetails> tdDetail = tdCommodityUserOrderService.findCommodityByOrderNo(orderNo,(byte) 0);
        if(null != tdDetail && tdDetail.size() > 0){
            for(TdCommodityOrderDetails td2:tdDetail){
                if(!StringUtils.isEmpty(td2.getCommodityBarCode())){
                    MallCommoditySpecs mallCommoditySpecs = mallCommodityService.selectSpecsByCommodityAndBarCode(td2.getCommodityId(), td2.getCommodityBarCode());
                    if(null != mallCommoditySpecs){
                        sysStoreStorkService.outStork(storeId,mallCommoditySpecs.getId(), td2.getCommodityId(), td2.getCommodityNum().longValue());
                    }else{
                        sysStoreStorkService.outStork(storeId,null, td2.getCommodityId(), td2.getCommodityNum().longValue());
                    }
                }else{
                    sysStoreStorkService.outStork(storeId,null, td2.getCommodityId(), td2.getCommodityNum().longValue());
                }
            }
        }
    }

    @Log
    @Token
    @ApiOperation("订单详情")
    @GetMapping("/orderDetail")
    public ResponseData<TdCommodityStoreOrderDetailResp> findOrderDetail(TdCommodityOrderNoRequest req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        TdCommodityStoreOrderDetailResp detailResp = tdCommodityUserOrderService.findStoreOrderDetailByOrderNo(req.getOrderNo(), Long.parseLong(getAttribute()), null);
        if (!StringUtils.isEmpty(detailResp)) {
            String headImg = userInfoService.getHeadImg(detailResp.getUserInfoId());
            detailResp.setHeadImg(headImg);
            SysStoreInfo sysStoreInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
            if (!StringUtils.isEmpty(sysStoreInfo)) {
                detailResp.setStoreName(sysStoreInfo.getStoreName());
                detailResp.setStoreImage(sysStoreInfo.getStoreImage());
                detailResp.setConnectWay(sysStoreInfo.getConnectWay());
            }
        } else {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        return ResponseData.success(detailResp);
    }

    @Log
    @Token
    @ApiOperation("审核申请的售后")
    @PostMapping("/checkAfterService")
    public ResponseData checkAfterService(@RequestBody TdCheckAfterServiceReq req) throws Exception{
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        Long storeLoginId = Long.parseLong(getAttributeForLoginId());
        Long storeId = Long.parseLong(getAttribute());

        SysStoreLoginInfo sysStoreLoginInfo = sysStoreLoginInfoService.selectByLoginInfoId(storeLoginId);

        if("-1".equals(req.getStatus())){
            return tdCommodityUserOrderService.checkAfterService(req,storeId,storeLoginId,sysStoreLoginInfo.getLoginName());
        }
        if("1".equals(req.getStatus())){
            ResponseData resp = tdCommodityUserOrderService.checkAfterService(req,storeId,storeLoginId,sysStoreLoginInfo.getLoginName());
            if(resp.getCodeId() != 1){
                return resp;
            }
            TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderService.findByOrderNo(req.getOrderNo());

            TdCommodityTradeOrder tdCommodityTradeOrder = tdCommodityUserOrderService.selectTradeOrderByOrderNo(req.getOrderNo());
            if(StringUtils.isEmpty(tdCommodityTradeOrder)){
                return ResponseData.fail(CodeIdEnum.NoneTradeOrder);
            }
            if(!"001".equals(tdCommodityTradeOrder.getThirdOrderNo())){
                //审核通过, 退款 --> 修改订单状态 --> 修改售后状态
                resp = WeChatRefundUtils.weichatOriginalRefund(wechatConfig,req.getOrderNo(),tdCommodityUserOrder.getActualAmount(),tdCommodityTradeOrder.getThirdOrderNo(), String.valueOf(tdCommodityUserOrder.getActualAmount().intValue()));
            }

            if(resp.getCodeId() != 1){
                return resp;
            }
            ResponseData result = tdCommodityUserOrderService.agreeAfterService(req, storeId, storeLoginId, sysStoreLoginInfo.getLoginName());
            if(result.getCodeId() == 1){
                // 扣除门店积分
                delStoreIntegral(req.getOrderNo(),storeId);
            }
            //修改优惠券
//            couponAfter(req.getOrderNo());
            //修改库存
            backStock(req.getOrderNo(),storeId);

            //修改优惠券记录表
//            tdCouponUseService.updateStatusByorderNo(req.getOrderNo(), (byte) 2);
            return result;
        }

        return ResponseData.fail();

    }

    @Log
    @Token
    @ApiOperation("售后记录")
    @GetMapping("/afterSaleRecord")
    public ResponseData<PageInfo<AppAfterSaleRecordResp>> afterSaleRecord(AppAfterSaleRecordReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        //从token中获取门店id并设置
        req.setStoreId(Long.parseLong(getAttribute()));
        PageInfo<AppAfterSaleRecordResp> pageInfo = tdCommodityUserOrderService.selectByStoreId(req);
        return ResponseData.success(pageInfo);
    }

    private void backStock(String orderNo,Long storeId){
        List<TdCommodityOrderDetails> details = tdCommodityUserOrderService.detailsByOrder(orderNo);
        if (ObjectUtils.isEmpty(details) || details.size() <= 0){
            return;
        }
        for(TdCommodityOrderDetails tdCommodity:details){
            if(!StringUtils.isEmpty(tdCommodity.getCommodityBarCode())){
                MallCommoditySpecs commoditySpecs = mallCommodityService.selectSpecsByCommodityAndBarCode(tdCommodity.getCommodityId(), tdCommodity.getCommodityBarCode());
                if (!ObjectUtils.isEmpty(commoditySpecs)){
//                    SysStoreStock stock = sysStoreStorkService.selectCountStock(storeId, commoditySpecs.getId());
//                    if (ObjectUtils.isEmpty(stock)){
//                        return;
//                    }
//                    stock.setNum(stock.getNum() + tdCommodity.getCommodityNum());
//                    sysStoreStorkService.updateStockNum(stock.getId(),stock.getNum());
                    //恢复补货记录剩余库存
                    sysStoreStorkService.retreatStork(storeId, commoditySpecs.getId(), tdCommodity.getCommodityId(), tdCommodity.getCommodityNum().longValue());
                }
            }else{
//                SysStoreStock stock = sysStoreStorkService.selectNoneSpecsStock(storeId, tdCommodity.getCommodityId());
//                if (ObjectUtils.isEmpty(stock)){
//                    return;
//                }
//                stock.setNum(stock.getNum() + tdCommodity.getCommodityNum());
//                sysStoreStorkService.updateStockNum(stock.getId(),stock.getNum());
                //恢复补货记录剩余库存
                sysStoreStorkService.retreatStork(storeId, null, tdCommodity.getCommodityId(), tdCommodity.getCommodityNum().longValue());
            }

        }
    }


    private void delStoreIntegral(String orderNo,Long storeId){
        SysStoreIntegralRecord record = sysStoreIntegralService.selectByOrderNo(orderNo);
        if(ObjectUtil.isEmpty(record)){
            return;
        }
        List<SysStoreIntegralRecordDetail> detailList = sysStoreIntegralService.selectByRecordId(record.getId());
        if(CollUtil.isEmpty(detailList)){
            return;
        }
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(storeId);
        if(ObjectUtil.isEmpty(storeInfo)){
            return;
        }
        SysStoreAccountInfo accountInfo = sysStoreInfoService.selectByStoreId(storeId);
        if(ObjectUtil.isEmpty(accountInfo)){
            return;
        }
        SysStoreAccountInfo accountInfo2 = new SysStoreAccountInfo();
        accountInfo2.setId(accountInfo.getId());
        accountInfo2.setPoint(accountInfo.getPoint().subtract(record.getIntegral()));
        sysStoreInfoService.updateAccountInfo(accountInfo2);

        StoreCommodityIntegralReq intReq = new StoreCommodityIntegralReq();
        intReq.setStoreId(storeId);
        intReq.setAccountId(accountInfo.getId());
        intReq.setIntegral(record.getIntegral());
        intReq.setOrderNo(orderNo);
        List<StoreCommodityIntegralDetialReq> list = new ArrayList<>();
        for (SysStoreIntegralRecordDetail recordDetail : detailList) {
            StoreCommodityIntegralDetialReq req = new StoreCommodityIntegralDetialReq();
            req.setCommodityName(recordDetail.getCommodityName());
            req.setCommodityId(recordDetail.getCommodityId());
            req.setBarCode(recordDetail.getBarCode());
            req.setSpecs(recordDetail.getCommoditySpecs());
            req.setIntegral(recordDetail.getIntegral());
            list.add(req);
        }
        intReq.setList(list);
        sysStoreIntegralService.insertCommodityIntegral(intReq,(byte)3);
    }



}
